#
# "@(#) $Id: RadioLibrary.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from Library import *
from Utils.Paths import *
from Utils.PListParser import *
from UI.RadioTrackDialog import *
from Player import *
from PLS import *
from M3U import *
import os
import traceback

_radioSingleton = None

class RadioTrack(Track):
	def __init__(self):
		Track.__init__(self)
		self.streams = None
		self.isStream = True
		self.explicit = False
		self.description = ""
		self.user = False

	def setPList(self,plist):
		self.isStream = True
		self.title = plist['Title']
		self.location = str(plist['Location'])
		self.bitRate = plist.get('Bit Rate',None)
		self.description = plist.get('Description','')
		self.genre = plist.get('Genre',None)
		self.explicit = plist.get('Explicit',False)
		self.user = plist.get('User',False)

	def getPList(self):
		plist = {}
		plist['Title']= self.title
		plist['Location'] = self.location
		plist['Bit Rate'] = self.bitRate
		plist['Description'] = self.description
		plist['Genre'] = self.genre
		plist['Explicit'] = self.explicit
		plist['User'] = self.user
		return plist
	
	def edit(self):
		dialog = RadioTrackDialog(self.getPList())
		ret = dialog.exec_loop()
		if ret == QDialog.Accepted:
			oldGenre = self.genre
			pList = dialog.unload()
			newGenre = pList['Genre']
			if oldGenre != newGenre:
				self.library.remove(self)
			self.setPList(pList)
			if oldGenre != newGenre:
				self.library.inject(self)
	
	def play(self):
		#print "going to play",self.stream
		LMusicPlayer.playTrack(self,self.library,None)
	
	def pause(self):
		LMusicPlayer.pause()
	
	def fetchStream(self):
		if self.streams == None:
			(path,ext) = os.path.splitext(self.location)
			#print ">>>>track lock name self",self.location,"__",self.name,"__",self
			if ext=='.pls':
				#print " parsing pls",self.location
				self.streams = fetchAndParsePLS(self.location)
				#print " GOT STREAM",self.streams
				#traceback.print_stack()
			elif ext=='.m3u':
				#print " parsing m3u",self.location
				self.streams = fetchAndParseM3U(self.location)	
				#print "got streams",self.streams
			else:
				traceback.print_stack()
				self.streams = [self.location]
			print "got stream",self.streams
		self.stream = self.streams[random.randint(0,len(self.streams)-1)]
	
	def bookmark(self):
		RadioLibrary.singleton().bookmark(self)

class RadioLibrary(QObject):
	def __init__(self):
		global _serverName
		QObject.__init__(self)
		self._genres = {}
		self.readXMLFile()
		#self.fetch()
	
	def filePath(self):
		return os.path.join(Library.mainLibrary().libraryPath(),"LsongsStations.xml")

	def readXMLFile(self):
		path = self.filePath()
		try:
			reader = PListReader()
			plist = reader.parse(path)
			self.setPList(plist[0])
		except:
			self.setPList({})
	
	def writeXMLFile(self):
		path = self.filePath()
		writer = PListWriter()
		writer.unparse([self.pList],path)
	
	def injectPList(self,plist):
		track = self.trackFromPList(plist)
		self.inject(track)
	
	def bookmark(self,track):
		oldTrack = self.findTrackWithTitle(track.title)
		if oldTrack:
			oldTrack.location = track.location
			oldTrack.bitRate = track.bitRate
		else:
			self.inject(track)

	def inject(self,track):
		genre = track.genre
		if not self._genres.has_key(genre):
			self._genres[genre] = []
		self._genres[genre].append(track)
		track.library = self
		self.emit(PYSIGNAL("injectedItem"),(self,track,genre))
	
	def findTrackWithTitle(self,title):
		title = unikode(title)
		for genreKey in self._genres.keys():
			genre = self._genres[genreKey]
			for track in genre:
				if unikode(track.title)==title:
					return track
		return None

	def remove(self,item):
		genre = item.genre
		try: self._genres[genre].remove(item)
		except: pass
		try:
			if len(self._genres[genre])==0:
				self._genres.pop(genre)
		except: pass
		self.emit(PYSIGNAL("removedItem"),(self,item))
			
	def userStations(self):
		userStations = []
		for genre in self._genres.keys():
			genreItem = self._genres[genre]
			for item in genreItem:
				try:
					if item.user:
						userStations.append(item)
				except: pass
		return userStations
	
	def injectStations(self,stations):
		for station in stations:
			self.inject(station)
	
	def genres(self):
		return self._genres.keys()
	
	def tracksForGenre(self,genre):
		try: return self._genres[genre]
		except: return None

	def trackFromPList(self,plist):
		track = RadioTrack()
		track.setPList(plist)
		return track

	def pListFromTrack(self,track):
		return track.getPList()
	
	def getPList(self):
		pList = {}
		for genre in self._genres.keys():
			tracks = self._genres[genre]
			genreItems = []
			for track in tracks:
				trackItem = self.pListFromTrack(track)
				genreItems.append(trackItem)
			pList[genre] = genreItems
		return pList
	def setPList(self,plist):
		self._genres = {}
		for genre in plist.keys():
			genreItems = plist[genre]
			tracks = []
			count = 0
			for item in genreItems:
				try:
					track = self.trackFromPList(item)
					track.library = self
					tracks.append(track)
				except:
					print "problem with",item
			self._genres[genre] = tracks
	pList = property(getPList,setPList)

	def addStream(self):
		addStreamDialog = RadioTrackDialog()
		ret = addStreamDialog.exec_loop()
		if ret==QDialog.Accepted:
			plist = addStreamDialog.unload()
			self.injectPList(plist)

	def static_singleton():
		global _radioSingleton
		if _radioSingleton==None:
			_radioSingleton = RadioLibrary()
		return _radioSingleton
	singleton = staticmethod(static_singleton)

if __name__=='__main__':
	l = RadioLibrary.singleton()
	print l.pList
	
